package com.hotacorp.opencloud.common.resourcecommon.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.web.client.RestTemplate;

import com.hotacorp.opencloud.common.commdata.PermitUrlProperties;
import com.hotacorp.opencloud.common.resourcecommon.exception.AuthAccessDeniedHandler;
import com.hotacorp.opencloud.common.resourcecommon.exception.AuthExceptionEntryPoint;
import com.hotacorp.opencloud.common.resourcecommon.exception.CustomUserAuthenticationConverter;

/**
 * 资源服务器认证、授权配置类
 * @author lwg
 *
 */
public class OpenCloudResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
	
	@Autowired
	@Qualifier("tokenInfoRestTemplate")
	private RestTemplate restTemplate;
	
	@Autowired
	public RemoteTokenServices remoteTokenServices;

	@Autowired
	private PermitUrlProperties permitUrlProperties ;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    	DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
    	accessTokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
    	remoteTokenServices.setRestTemplate(restTemplate);
        resources.tokenServices(remoteTokenServices);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint()).accessDeniedHandler(new AuthAccessDeniedHandler());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    	http.csrf().disable();
    	http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll();// 配置OPTIONS方法都可以访问
    	http.authorizeRequests().antMatchers(permitUrlProperties.getIgnored()).permitAll();// 配置匿名可以访问
        http.authorizeRequests().anyRequest().authenticated(); // 配置其他的，必须认证后才可以访问
    }

}
